package cn.xx.user.controller;

import cn.xx.basic.util.AjaxResult;
import cn.xx.user.constant.WechatConstant;
import cn.xx.user.dto.UserDto;
import cn.xx.user.service.IWechatService;
import org.omg.CORBA.OBJECT_NOT_EXIST;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;

    /**
     * 跳转到微信登录界面(拉取二维码)
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin() {
        return "redirect:"+WechatConstant.LOGIN_URL
                .replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
    }

    /**
     * 二维码扫完之后，调用回调接口
     * @param code  授权码
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code) {
        //跳转到门户网站页面
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }

    /**
     * 处理回调方法
     * @return
     */
    @PostMapping("/handleCallBackMethod")
    @ResponseBody
    public AjaxResult handleCallBackMethod(@RequestBody Map<String,String> map) {
        try {
            //处理回调方法
            Map<String, Object> resultMap = wechatService.handleCallBackMethod(map);
            // resultMap数据传递给前端
            return AjaxResult.me().setResultObject(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().me().setSuccess(false).setMsg(e.getMessage());
        }
    }

    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody UserDto userDto) {
        try {
            Map<String, Object> resultMap = wechatService.binder(userDto);
            return AjaxResult.me().setResultObject(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult().me().setSuccess(false).setMsg(e.getMessage());
        }

    }


}
